<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>WebSocket测试</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 20px;
            line-height: 1.6;
        }
        .container {
            max-width: 800px;
            margin: 0 auto;
            border: 1px solid #ddd;
            padding: 20px;
            border-radius: 5px;
        }
        .panel {
            margin-bottom: 20px;
            padding: 15px;
            border: 1px solid #ddd;
            border-radius: 5px;
        }
        .control {
            margin-bottom: 10px;
        }
        .control label {
            display: inline-block;
            width: 120px;
        }
        .control input, .control select {
            padding: 5px;
            width: 250px;
        }
        button {
            padding: 8px 15px;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            margin-right: 10px;
        }
        button:hover {
            background-color: #45a049;
        }
        button:disabled {
            background-color: #cccccc;
            cursor: not-allowed;
        }
        #messages {
            height: 300px;
            border: 1px solid #ddd;
            padding: 10px;
            overflow-y: auto;
            margin-top: 20px;
            background-color: #f9f9f9;
        }
        .message {
            margin-bottom: 5px;
            padding: 5px;
            border-bottom: 1px solid #eee;
        }
        .received {
            color: blue;
        }
        .sent {
            color: green;
        }
        .error {
            color: red;
        }
        .status {
            color: purple;
        }
        .success {
            color: green;
            font-weight: bold;
        }
        .hidden {
            display: none;
        }
        .step-indicator {
            display: flex;
            margin-bottom: 20px;
        }
        .step {
            flex: 1;
            text-align: center;
            padding: 10px;
            background-color: #f0f0f0;
            border: 1px solid #ddd;
            position: relative;
        }
        .step.active {
            background-color: #e7f7e7;
            border-color: #4CAF50;
            font-weight: bold;
        }
        .step.completed {
            background-color: #dff0d8;
            border-color: #4CAF50;
        }
        .step:not(:last-child):after {
            content: "";
            position: absolute;
            top: 50%;
            right: -10px;
            width: 20px;
            height: 2px;
            background-color: #ddd;
            z-index: 1;
        }
        .step.completed:not(:last-child):after {
            background-color: #4CAF50;
        }
    </style>
</head>
<body>
    <div class="container">
        <h2>WebSocket测试工具</h2>
        
        <!-- 步骤指示器 -->
        <div class="step-indicator">
            <div class="step active" id="step-login">1. 登录</div>
            <div class="step" id="step-connect">2. 连接WebSocket</div>
            <div class="step" id="step-task">3. 启动任务</div>
        </div>
        
        <!-- 登录面板 -->
        <div class="panel" id="loginPanel">
            <h3>登录</h3>
            <div class="control">
                <label for="username">用户名:</label>
                <input type="text" id="username" value="admin">
            </div>
            <div class="control">
                <label for="password">密码:</label>
                <input type="password" id="password" value="123456">
            </div>
            <div class="control">
                <label for="loginUrl">登录接口:</label>
                <input type="text" id="loginUrl" value="http://localhost:8080/doctor/login">
            </div>
            <div>
                <button id="loginBtn">登录</button>
            </div>
        </div>
        
        <!-- WebSocket连接面板 -->
        <div class="panel" id="wsPanel">
            <h3>连接设置</h3>
            <div class="control">
                <label for="sessionId">会话ID:</label>
                <input type="text" id="sessionId" value="test-session-001">
            </div>
            <div class="control">
                <label for="serverUrl">服务器地址:</label>
                <input type="text" id="serverUrl" value="ws://localhost:8080/websocket/">
            </div>
            <div>
                <button id="connectBtn" disabled>连接</button>
                <button id="disconnectBtn" disabled>断开</button>
                <button id="checkStatusBtn" disabled>检查状态</button>
            </div>
        </div>
        
        <!-- 任务控制面板 -->
        <div class="panel" id="taskPanel">
            <h3>任务控制</h3>
            <div class="control">
                <label for="mapType">数据类型:</label>
                <select id="mapType">
                    <option value="300">300</option>
                    <option value="600">600</option>
                    <option value="900">900</option>
                </select>
            </div>
            <div>
                <button id="startTaskBtn" disabled>启动任务</button>
                <button id="stopTaskBtn" disabled>停止任务</button>
            </div>
        </div>
        
        <!-- 消息发送面板 -->
        <div class="panel" id="msgPanel">
            <h3>发送消息</h3>
            <div class="control">
                <input type="text" id="messageInput" placeholder="输入要发送的消息" style="width: 70%;">
                <button id="sendBtn" disabled>发送</button>
            </div>
        </div>
        
        <h3>消息记录</h3>
        <div id="messages"></div>
    </div>
    
    <script>
        // 全局变量
        let socket;
        let token = '';
        
        // DOM元素
        const username = document.getElementById('username');
        const password = document.getElementById('password');
        const loginUrl = document.getElementById('loginUrl');
        const loginBtn = document.getElementById('loginBtn');
        
        const sessionId = document.getElementById('sessionId');
        const serverUrl = document.getElementById('serverUrl');
        const connectBtn = document.getElementById('connectBtn');
        const disconnectBtn = document.getElementById('disconnectBtn');
        const checkStatusBtn = document.getElementById('checkStatusBtn');
        
        const mapType = document.getElementById('mapType');
        const startTaskBtn = document.getElementById('startTaskBtn');
        const stopTaskBtn = document.getElementById('stopTaskBtn');
        
        const messageInput = document.getElementById('messageInput');
        const sendBtn = document.getElementById('sendBtn');
        const messagesDiv = document.getElementById('messages');
        
        // 步骤指示器
        const stepLogin = document.getElementById('step-login');
        const stepConnect = document.getElementById('step-connect');
        const stepTask = document.getElementById('step-task');
        
        // 添加消息到消息记录区域
        function addMessage(message, type) {
            const messageElement = document.createElement('div');
            messageElement.className = `message ${type}`;
            messageElement.textContent = `[${new Date().toLocaleTimeString()}] ${message}`;
            messagesDiv.appendChild(messageElement);
            messagesDiv.scrollTop = messagesDiv.scrollHeight;
        }
        
        // 更新步骤状态
        function updateStepStatus(step, status) {
            stepLogin.className = 'step';
            stepConnect.className = 'step';
            stepTask.className = 'step';
            
            if (step >= 1) {
                stepLogin.className = 'step completed';
            }
            if (step >= 2) {
                stepConnect.className = 'step completed';
            }
            if (step >= 3) {
                stepTask.className = 'step completed';
            }
            
            if (step === 1) {
                stepLogin.className = 'step active';
            } else if (step === 2) {
                stepConnect.className = 'step active';
            } else if (step === 3) {
                stepTask.className = 'step active';
            }
        }
        
        // 登录
        loginBtn.addEventListener('click', async () => {
            const user = username.value.trim();
            const pwd = password.value.trim();
            const url = loginUrl.value.trim();
            
            if (!user || !pwd) {
                addMessage('请输入用户名和密码', 'error');
                return;
            }
            
            addMessage(`尝试登录: ${user}`, 'status');
            
            try {
                const response = await fetch(url, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        username: user,
                        password: pwd
                    })
                });
                
                const data = await response.json();
                addMessage(`登录结果: ${JSON.stringify(data)}`, 'status');
                
                if (data.code === 200) {
                    addMessage(`登录成功: ${data.msg || '认证通过'}`, 'success');
                    // 保存token如果有的话
                    if (data.data && data.data.token) {
                        token = data.data.token;
                        addMessage(`获取到令牌`, 'status');
                    }
                    
                    // 启用连接按钮和状态检查按钮
                    connectBtn.disabled = false;
                    checkStatusBtn.disabled = false;
                    
                    // 更新步骤状态
                    updateStepStatus(1);
                } else {
                    addMessage(`登录失败: ${data.msg || '认证失败'}`, 'error');
                }
            } catch (error) {
                addMessage(`登录出错: ${error.message}`, 'error');
            }
        });
        
        // 连接WebSocket
        connectBtn.addEventListener('click', () => {
            const id = sessionId.value.trim();
            const url = serverUrl.value.trim() + id;
            
            if (!id) {
                addMessage('请输入会话ID', 'error');
                return;
            }
            
            addMessage(`尝试连接WebSocket: ${url}`, 'status');
            
            try {
                socket = new WebSocket(url);
                
                socket.onopen = (event) => {
                    addMessage(`WebSocket连接已建立: ${url}`, 'success');
                    connectBtn.disabled = true;
                    disconnectBtn.disabled = false;
                    startTaskBtn.disabled = false;
                    sendBtn.disabled = false;
                    
                    // 更新步骤状态
                    updateStepStatus(2);
                };
                
                socket.onmessage = (event) => {
                    addMessage(`收到消息: ${event.data}`, 'received');
                    
                    // 尝试解析JSON
                    try {
                        const data = JSON.parse(event.data);
                        if (data.type === 'taskStarted') {
                            stopTaskBtn.disabled = false;
                            // 更新步骤状态
                            updateStepStatus(3);
                        } else if (data.type === 'taskStopped') {
                            stopTaskBtn.disabled = true;
                        }
                    } catch (e) {
                        // 不是JSON格式，不处理
                    }
                };
                
                socket.onclose = (event) => {
                    addMessage(`WebSocket连接已关闭，代码: ${event.code}，原因: ${event.reason}`, 'status');
                    connectBtn.disabled = false;
                    disconnectBtn.disabled = true;
                    startTaskBtn.disabled = true;
                    stopTaskBtn.disabled = true;
                    sendBtn.disabled = true;
                };
                
                socket.onerror = (error) => {
                    addMessage(`WebSocket错误: ${error}`, 'error');
                };
            } catch (error) {
                addMessage(`创建WebSocket失败: ${error.message}`, 'error');
            }
        });
        
        // 断开WebSocket连接
        disconnectBtn.addEventListener('click', () => {
            if (socket && socket.readyState === WebSocket.OPEN) {
                socket.close();
                addMessage('WebSocket连接已断开', 'status');
                connectBtn.disabled = false;
                disconnectBtn.disabled = true;
                startTaskBtn.disabled = true;
                stopTaskBtn.disabled = true;
                sendBtn.disabled = true;
                
                // 更新步骤状态
                updateStepStatus(1);
            }
        });
        
        // 检查WebSocket状态
        checkStatusBtn.addEventListener('click', async () => {
            const id = sessionId.value.trim();
            if (!id) {
                addMessage('请输入会话ID', 'error');
                return;
            }
            
            try {
                let headers = { 'Content-Type': 'application/json' };
                if (token) {
                    headers['token'] = token; // 添加令牌到请求头
                }
                
                const response = await fetch(`http://localhost:8080/map/ws-status?sessionId=${id}`, {
                    headers: headers
                });
                
                const data = await response.json();
                addMessage(`WebSocket状态: ${JSON.stringify(data)}`, 'status');
            } catch (error) {
                addMessage(`检查状态失败: ${error.message}`, 'error');
            }
        });
        
        // 启动任务
        startTaskBtn.addEventListener('click', async () => {
            const id = sessionId.value.trim();
            const type = mapType.value;
            
            if (!id) {
                addMessage('请输入会话ID', 'error');
                return;
            }
            
            addMessage(`尝试启动任务，类型: ${type}`, 'status');
            
            try {
                let headers = { 'Content-Type': 'application/json' };
                if (token) {
                    headers['token'] = token; // 添加令牌到请求头
                }
                
                const response = await fetch('http://localhost:8080/map/start', {
                    method: 'POST',
                    headers: headers,
                    body: JSON.stringify({
                        sessionId: id,
                        type: type
                    })
                });
                
                const data = await response.json();
                addMessage(`启动任务结果: ${JSON.stringify(data)}`, 'status');
                
                if (data.code === 200) {
                    addMessage(`任务启动成功: ${data.msg || '开始接收数据'}`, 'success');
                    stopTaskBtn.disabled = false;
                    
                    // 更新步骤状态
                    updateStepStatus(3);
                } else {
                    addMessage(`任务启动失败: ${data.msg || '操作失败'}`, 'error');
                }
            } catch (error) {
                addMessage(`启动任务失败: ${error.message}`, 'error');
            }
        });
        
        // 停止任务
        stopTaskBtn.addEventListener('click', async () => {
            const id = sessionId.value.trim();
            
            if (!id) {
                addMessage('请输入会话ID', 'error');
                return;
            }
            
            addMessage(`尝试停止任务`, 'status');
            
            try {
                let headers = { 'Content-Type': 'application/json' };
                if (token) {
                    headers['token'] = token; // 添加令牌到请求头
                }
                
                const response = await fetch('http://localhost:8080/map/stop', {
                    method: 'POST',
                    headers: headers,
                    body: JSON.stringify({
                        sessionId: id
                    })
                });
                
                const data = await response.json();
                addMessage(`停止任务结果: ${JSON.stringify(data)}`, 'status');
                
                if (data.code === 200) {
                    addMessage(`任务已停止: ${data.msg || '数据接收已停止'}`, 'success');
                    stopTaskBtn.disabled = true;
                    
                    // 更新步骤状态
                    updateStepStatus(2);
                } else {
                    addMessage(`停止任务失败: ${data.msg || '操作失败'}`, 'error');
                }
            } catch (error) {
                addMessage(`停止任务失败: ${error.message}`, 'error');
            }
        });
        
        // 发送消息
        sendBtn.addEventListener('click', () => {
            const message = messageInput.value.trim();
            
            if (!message) {
                addMessage('请输入要发送的消息', 'error');
                return;
            }
            
            if (socket && socket.readyState === WebSocket.OPEN) {
                socket.send(message);
                addMessage(`发送消息: ${message}`, 'sent');
                messageInput.value = '';
            } else {
                addMessage('WebSocket未连接，无法发送消息', 'error');
            }
        });
        
        // 回车发送消息
        messageInput.addEventListener('keypress', (event) => {
            if (event.key === 'Enter' && !sendBtn.disabled) {
                sendBtn.click();
            }
        });
        
        // 页面加载时添加初始状态消息
        window.addEventListener('load', () => {
            addMessage('WebSocket测试工具已加载，请先登录', 'status');
            updateStepStatus(1);
        });
    </script>
</body>
</html> 